package com.baor.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baor.dao.CustomerDao;
import com.baor.dao.EquipmentHolderOrdersDao;
import com.baor.domain.CustomerVO;
import com.baor.domain.Equipment_holder_orders;
import com.baor.service.TeamService;
import com.baor.util.GeneratorCode;
import com.baor.util.R;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
@Slf4j
@Service
@RequiredArgsConstructor
public class TeamServiceImpl implements TeamService{
    @Autowired
    private  CustomerDao customerDao;
    @Autowired
    private EquipmentHolderOrdersDao equipmentHolderOrdersDao;
    /**
     * 查询所有团队及成员 - 按团队分组返回
     */
    @Override
    public List<Map<String, Object>> getAllTeamsWithMembers(String nickname, String phone) {
        // 1. 带条件查询用户（若参数为空则查全部符合条件的用户）
        List<CustomerVO> allUsers = customerDao.selectByCondition(nickname, phone);

        if (CollectionUtils.isEmpty(allUsers)) {
            return Collections.emptyList();
        }

        // 2. 按团队编号分组
        Map<String, List<CustomerVO>> teamUserMap = allUsers.stream()
                .collect(Collectors.groupingBy(CustomerVO::getTeamcode));

        // 3. 为每个团队构建结构
        List<Map<String, Object>> result = new ArrayList<>();

        for (Map.Entry<String, List<CustomerVO>> entry : teamUserMap.entrySet()) {
            String teamCode = entry.getKey();
            List<CustomerVO> teamUsers = entry.getValue();

            // 分离团长和普通成员
            CustomerVO leader = null;
            List<CustomerVO> members = new ArrayList<>();

            for (CustomerVO user : teamUsers) {
                if ("1".equals(user.getIsLeader())) {
                    leader = user;
                } else {
                    members.add(user);
                }
            }

            // 构建团队信息
            Map<String, Object> teamInfo = new LinkedHashMap<>();
            teamInfo.put("teamCode", teamCode);
            teamInfo.put("leader", buildUserInfo(leader)); // 团长信息
            teamInfo.put("members", buildMembersInfo(members)); // 成员列表
            teamInfo.put("memberCount", teamUsers.size()); // 团队总人数
            teamInfo.put("regularMemberCount", members.size()); // 普通成员人数

            result.add(teamInfo);
        }

        return result;
    }

    /**
     * 构建用户信息
     */

    public Map<String, Object> buildUserInfo(CustomerVO user) {
        if (user == null) {
            return null;
        }

        Map<String, Object> userInfo = new LinkedHashMap<>();
        userInfo.put("id", user.getId());
        String nickname = user.getNickname();
        userInfo.put("nickname", nickname);
        userInfo.put("phone", user.getPhone());
        userInfo.put("teamCode", user.getTeamcode());
        userInfo.put("isLeader", user.getIsLeader());
        userInfo.put("joinTime", user.getJoinTime());
        userInfo.put("remark", user.getRemark());
        userInfo.put("equipmentCodes", user.getEquipmentCodes());
        userInfo.put("inviterNickname",user.getInviterNickname());
        userInfo.put("inviterPhone",user.getInviterPhone());
        System.out.println(userInfo);
        return userInfo;
    }

    /**
     * 构建成员列表信息
     */

    public List<Map<String, Object>> buildMembersInfo(List<CustomerVO> members) {
        return members.stream()
                .map(this::buildUserInfo)
                .collect(Collectors.toList());
    }
    @Override
    public int updateTeam(@RequestParam Map<String, Object> params) {
        String nickname = params.getOrDefault("nickname", "").toString().trim();
        String phone = params.getOrDefault("phone", "").toString().trim();
        Integer id = Integer.parseInt(params.getOrDefault("id", "").toString().trim());
        String teamcode = params.getOrDefault("teamcode", "").toString().trim();
        String remark = params.getOrDefault("remark", "").toString().trim();
        CustomerVO customer = new CustomerVO();
        customer.setNickname(nickname);
        customer.setPhone(phone);
        customer.setId(id);
        customer.setTeamcode(teamcode);
        customer.setRemark(remark);
        int row = this.customerDao.updateById(customer);
       return row;
    }

    @Override

    public int addHolder(Map<String, Object> params) {
        String teamcode = params.getOrDefault("teamcode", "").toString().trim();
        String id = params.getOrDefault("id", "").toString().trim();
        Integer parentagentid = (Integer) params.get("parentagentid");
        CustomerVO customerVO = this.customerDao.selectById(id);
        Equipment_holder_orders equipmentHolderOrders = new Equipment_holder_orders();
        equipmentHolderOrders.setUsername(customerVO.getNickname());
        equipmentHolderOrders.setPhone(customerVO.getPhone());
        equipmentHolderOrders.setUsername(customerVO.getNickname());
        equipmentHolderOrders.setPayTime(String.valueOf(LocalDateTime.now()));
        equipmentHolderOrders.setPayMethod("后台添加");
        equipmentHolderOrders.setMoney(BigDecimal.valueOf(9500));
        equipmentHolderOrders.setRemarks("代理商费用");
        //订单编号
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String workOrderNo = "XQ" + LocalDateTime.now().format(formatter);
        equipmentHolderOrders.setOrderCode(workOrderNo);
        equipmentHolderOrders.setRole(1);
        this.equipmentHolderOrdersDao.insert(equipmentHolderOrders);
        if(customerVO.getTeamcode()!= null){
            return 0;
        }
        if(parentagentid != null && parentagentid == 0) {

            String newTeamcode = String.valueOf(new Random().nextInt(900000) + 100000);
            GeneratorCode.generatorCode(newTeamcode, newTeamcode);
            LambdaUpdateWrapper<CustomerVO> wrapper = new LambdaUpdateWrapper<>();
            wrapper.set(CustomerVO::getIsHolder,1)
                    .set(CustomerVO::getTeamcode,newTeamcode)
                    .set(CustomerVO::getIsAgent,1)
                    .eq(CustomerVO::getId,id);
            int update = this.customerDao.update(wrapper);
            return update;
        }else {
            LambdaUpdateWrapper<CustomerVO> wrapper = new LambdaUpdateWrapper<>();
            wrapper.set(CustomerVO::getIsHolder,0)
                    .set(CustomerVO::getIsAgent,1)
                    .set(CustomerVO::getTeamcode,teamcode)
                    .eq(CustomerVO::getId,id);
            int update = this.customerDao.update(wrapper);
            return update ;
        }

    }

    @Override
    public int bind(Map<String, Object> params) {
        Integer id = (Integer) params.get("id");
        Integer bindid = (Integer) params.get("bindid");
        LambdaUpdateWrapper<CustomerVO> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(CustomerVO::getBindid,bindid)
                .eq(CustomerVO::getId,id);
        int update = this.customerDao.update(wrapper);
        return update;
    }


}
